<template>
  <div class="websocket-tester">
    <el-card class="tester-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span>WebSocket 消息测试</span>
      </div>
      
      <el-form :model="form" label-width="100px" size="small">
        <!-- 用户ID -->
        <el-form-item label="用户ID:" required>
          <el-input 
            v-model="form.userId" 
            placeholder="请输入用户ID"
            clearable
          />
        </el-form-item>
        
        <!-- 消息类型 -->
        <el-form-item label="消息类型:" required>
          <el-select v-model="form.messageType" placeholder="请选择消息类型" style="width: 100%">
            <el-option label="心跳消息" value="heartbeat" />
            <el-option label="文本消息" value="text" />
            <el-option label="推送坐标" value="push_location" />
            <el-option label="拉取坐标" value="pull_location" />
            <el-option label="自定义消息" value="custom" />
          </el-select>
        </el-form-item>
        
        <!-- 消息内容 -->
        <el-form-item 
          label="消息内容:" 
          v-if="form.messageType === 'text' || form.messageType === 'custom'"
        >
          <el-input 
            v-model="form.messageContent" 
            type="textarea" 
            :rows="3"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        
        <!-- 接收者ID -->
        <el-form-item 
          label="接收者ID:" 
          v-if="form.messageType === 'text'"
        >
          <el-input 
            v-model="form.toUserId" 
            placeholder="请输入接收者ID"
            clearable
          />
        </el-form-item>
        
        <!-- 线路ID -->
        <el-form-item 
          label="线路ID:" 
          v-if="form.messageType === 'text'"
        >
          <el-input 
            v-model="form.lineId" 
            placeholder="请输入线路ID"
            clearable
          />
        </el-form-item>
        
        <!-- 坐标信息 -->
        <el-form-item 
          label="经度:" 
          v-if="form.messageType === 'push_location'"
        >
          <el-input 
            v-model="form.longitude" 
            placeholder="请输入经度"
            clearable
          />
        </el-form-item>
        
        <el-form-item 
          label="纬度:" 
          v-if="form.messageType === 'push_location'"
        >
          <el-input 
            v-model="form.latitude" 
            placeholder="请输入纬度"
            clearable
          />
        </el-form-item>
        
        <el-form-item 
          label="手机号:" 
          v-if="form.messageType === 'push_location'"
        >
          <el-input 
            v-model="form.phone" 
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        
        <el-form-item 
          label="头像:" 
          v-if="form.messageType === 'push_location'"
        >
          <el-input 
            v-model="form.avatar" 
            placeholder="请输入头像URL"
            clearable
          />
        </el-form-item>
        
        <!-- 用户ID列表 -->
        <el-form-item 
          label="用户ID列表:" 
          v-if="form.messageType === 'pull_location'"
        >
          <el-input 
            v-model="form.userIds" 
            placeholder="请输入用户ID，多个用逗号分隔"
            clearable
          />
        </el-form-item>
        
        <!-- 发送按钮 -->
        <el-form-item>
          <el-button 
            type="primary" 
            @click="sendMessage"
            :loading="sending"
            :disabled="!form.userId || !form.messageType"
          >
            发送消息
          </el-button>
          
          <el-button @click="clearForm">清空表单</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 消息历史 -->
      <div class="message-history" v-if="messageHistory.length > 0">
        <h4>消息历史</h4>
        <div class="history-list">
          <div 
            v-for="(msg, index) in messageHistory" 
            :key="index"
            class="history-item"
          >
            <div class="history-header">
              <span class="time">{{ formatTime(msg.timestamp) }}</span>
              <span class="type">{{ msg.type }}</span>
              <span class="status" :class="msg.status">
                {{ msg.status === 'success' ? '成功' : '失败' }}
              </span>
            </div>
            <div class="history-content">
              <pre>{{ JSON.stringify(msg.data, null, 2) }}</pre>
            </div>
          </div>
        </div>
        
        <el-button 
          type="text" 
          @click="clearHistory"
          style="margin-top: 10px"
        >
          清空历史
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'WebSocketTester',
  data() {
    return {
      sending: false,
      form: {
        userId: '',
        messageType: 'heartbeat',
        messageContent: '',
        toUserId: '',
        lineId: '',
        longitude: '',
        latitude: '',
        phone: '',
        avatar: '',
        userIds: ''
      },
      messageHistory: []
    };
  },
  mounted() {
    // 监听WebSocket消息事件
    this.$onWebSocket('message', this.onMessageReceived);
    this.$onWebSocket('error', this.onErrorReceived);
  },
  methods: {
    /**
     * 发送消息
     */
    async sendMessage() {
      if (!this.form.userId) {
        this.$message.warning('请输入用户ID');
        return;
      }
      
      this.sending = true;
      const timestamp = Date.now();
      
      try {
        let result;
        
        switch (this.form.messageType) {
          case 'heartbeat':
            result = await this.$websocket.sendHeartbeatMessage(this.form.userId);
            break;
            
          case 'text':
            if (!this.form.messageContent) {
              this.$message.warning('请输入消息内容');
              return;
            }
            result = await this.$websocket.sendTextMessage(
              this.form.userId,
              this.form.toUserId || 0,
              this.form.lineId || 0,
              this.form.messageContent
            );
            break;
            
          case 'push_location':
            if (!this.form.longitude || !this.form.latitude) {
              this.$message.warning('请输入坐标信息');
              return;
            }
            result = await this.$websocket.pushLocation(
              this.form.userId,
              this.form.phone || '',
              this.form.avatar || '',
              this.form.longitude,
              this.form.latitude
            );
            break;
            
          case 'pull_location':
            if (!this.form.userIds) {
              this.$message.warning('请输入用户ID列表');
              return;
            }
            const userIds = this.form.userIds.split(',').map(id => id.trim());
            result = await this.$websocket.pullLocation(userIds, this.form.userId);
            break;
            
          case 'custom':
            if (!this.form.messageContent) {
              this.$message.warning('请输入消息内容');
              return;
            }
            result = await this.$websocket.sendMessage(
              'custom',
              { content: this.form.messageContent },
              this.form.userId
            );
            break;
        }
        
        // 记录成功消息
        this.addToHistory({
          type: this.form.messageType,
          data: this.form,
          status: 'success',
          timestamp
        });
        
        this.$message.success('消息发送成功');
        
      } catch (error) {
        // 记录失败消息
        this.addToHistory({
          type: this.form.messageType,
          data: this.form,
          status: 'error',
          error: error.message,
          timestamp
        });
        
        this.$message.error(`消息发送失败: ${error.message}`);
      } finally {
        this.sending = false;
      }
    },
    
    /**
     * 清空表单
     */
    clearForm() {
      this.form = {
        userId: this.form.userId, // 保留用户ID
        messageType: 'heartbeat',
        messageContent: '',
        toUserId: '',
        lineId: '',
        longitude: '',
        latitude: '',
        phone: '',
        avatar: '',
        userIds: ''
      };
    },
    
    /**
     * 清空历史
     */
    clearHistory() {
      this.messageHistory = [];
    },
    
    /**
     * 添加到历史记录
     */
    addToHistory(message) {
      this.messageHistory.unshift(message);
      // 只保留最近50条记录
      if (this.messageHistory.length > 50) {
        this.messageHistory = this.messageHistory.slice(0, 50);
      }
    },
    
    /**
     * 收到消息回调
     */
    onMessageReceived(data) {
      this.addToHistory({
        type: 'received',
        data: data,
        status: 'success',
        timestamp: Date.now()
      });
    },
    
    /**
     * 收到错误回调
     */
    onErrorReceived(data) {
      this.addToHistory({
        type: 'error',
        data: data,
        status: 'error',
        timestamp: Date.now()
      });
    },
    
    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN');
    }
  }
};
</script>

<style scoped>
.websocket-tester {
  margin: 20px 0;
}

.tester-card {
  max-width: 600px;
}

.message-history {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.message-history h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
}

.time {
  color: #909399;
}

.type {
  font-weight: 500;
  color: #409eff;
}

.status {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
}

.status.success {
  background-color: #f0f9ff;
  color: #67c23a;
}

.status.error {
  background-color: #fef0f0;
  color: #f56c6c;
}

.history-content {
  background-color: #fff;
  padding: 8px;
  border-radius: 3px;
  border: 1px solid #e4e7ed;
}

.history-content pre {
  margin: 0;
  font-size: 12px;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>
